import { ref, watch, toValue, isRef } from 'vue'

export function useImgUrlToBase64(url) {
  const base64 = ref()

  if (isRef(url) || typeof url === 'function') {
    watch(url, transform, {
      immediate: true
    })
  } else {
    transform()
  }

  async function transform() {
    const value = toValue(url)

    base64.value = value ? await imgUrlToBase64(value) : undefined
  }

  function imgUrlToBase64(url) {
    return new Promise(resolve => {
      const t = new Date().getTime()
      url += url.includes('?') ? `&t=${t}` : `?t=${t}`

      let image = new Image()
      image.src = url
      image.crossOrigin = 'Anonymous'
      image.addEventListener('load', () => {
        if (!image) return
        let canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const ctx = canvas.getContext('2d')
        ctx?.drawImage(image, 0, 0, image.width, image.height)
        const dataURL = canvas.toDataURL('image/' + getExt(url), 0.1)

        resolve(dataURL)
        canvas.remove()
        image.remove()
        // 不置空内存没有释放
        canvas = null
        image = null
      })
      image.addEventListener('error', () => {
        resolve(undefined)
        image = null
      })
    })
  }

  function getExt(url) {
    const regex = /\.([0-9a-z]+)(?:[\?#]|$)/i
    return (url.match(regex) || [])[1]
  }

  return {
    base64
  }
}
